<template>
  <div class="kxy-paper" ref="paper" v-loading="dataListLoading">
    <el-alert type="info">
      <template slot="title">
        <p style="margin: 0;display: flex;align-items: flex-start;padding-right: 5px">
          <span style="width: 35px">提示:</span>
          <span style="flex: 1">需要新建子分类、重命名、删除分类请单击右键操作</span>
        </p>
      </template>
    </el-alert>
<!--    <el-button style="margin: 10px 0 0 10px" type="primary" @click="_ => add_edit_dialog(1)" class="el-icon-plus">新增分类</el-button>-->
    <el-tree
      ref="tree"
      :data="dataList"
      :default-expanded-keys="[-1, 0]"
      node-key="id"
      highlight-current
      accordion
      @node-click="setCurrent($event,bool)"
      @node-drop="handleDrop"
      :allow-drop="allowDrop"
      draggable
    >
      <div class="custom-tree-node" slot-scope="{node, data}" @mouseup="mouseup($event,node,data)">
        <div class="custom-tree-node-box">
          <div>
            <img v-if="data.parentId >= 0" width="20" height="20" src="/static/img/user/dept.png" />
            <img v-else width="20" height="20" src="/static/img/user/dept-group.png" />
            <!--<input type="text" :value="node.label" @change="modify($event,data)"/>-->
          </div>
          <div class="label">{{data.name}}</div>
          <div class="actions"></div>
        </div>
      </div>
    </el-tree>
    <ul :style="paperList" class="paperList">
      <li>
        <div v-if="this.url.cateType === 1">
          <el-button type="text" v-if="that_data.parentId !== '0' && url.cateType === 1" @click="_ => add_edit_dialog(1)" class="el-icon-plus">新增分类</el-button>
<!--          <el-button type="text" v-else  @click="_ => add_edit_dialog(1)" class="el-icon-plus">新增分类</el-button>-->
        </div>
        <div v-if="this.url.cateType === 2">
          <el-button type="text" v-if="url.cateType === 2" @click="_ => add_edit_dialog(1)" class="el-icon-plus">新增分类</el-button>
        </div>
      </li>
      <li>
        <el-button type="text" @click="_ => add_edit_dialog(2)" class="el-icon-edit">重命名</el-button>
      </li>
      <li>
<!--        v-if="that_data.parentId >= 0"-->
        <el-button type="text" @click="_remove" class="el-icon-delete">删除分类</el-button>
      </li>
    </ul>
    <el-dialog
      :title="parseInt(dialogcate) === 1?'新增分类': '更改名称'"
      :visible.sync="dialogFormAddVisible"
      :close-on-click-modal="false"
      :width="this.url.type === 1 ? '50%' : '400px'"
      :close-on-press-escape="false"
      append-to-body
      center
    >
      <div class="remove-papercate">
        <el-form :model="dataForm" :inline="true" @keyup.enter.native="add_edit">
          <el-col>
<!--            :label="parseInt(dialogFormAddVisible) === 1?'新增分类':'新分类名称'"-->
            <el-form-item label="名称" prop="name">
              <el-input v-model="dataForm.name" placeholder="分类名称不多于14个字符" clearable />
            </el-form-item>
            <el-form-item label="排序" prop="sort" v-if="this.url.prace === 1">
              <el-input v-model="dataForm.sort" placeholder="请输入排序" clearable />
            </el-form-item>
          </el-col>
<!--          <el-form-item :label="parseInt(dialogFormAddVisible) === 1?'上级分类':'旧分类名称'">-->
<!--            <el-input v-model="that_data.name" readonly disabled />-->
<!--          </el-form-item>-->
          <el-form-item v-if="this.url.type === 1" >
            <div style="display: flex;justify-content: space-between">
              <div>
                <el-image  src="static/img/exam/formalexam.png" /><br />
                <div style="text-align: center">
                  <el-radio v-model="dataForm.templateNum"  label="0">0</el-radio>
                </div>
              </div>
              <div  style="margin: 0 10px">
                <el-image  src="static/img/exam/weeklyexam.png" /><br />
                <div style="text-align: center">
                  <el-radio v-model="dataForm.templateNum" label="1">1</el-radio>
                </div>
              </div>
              <div>
                <el-image  src="static/img/exam/specialexam.png" /><br />
                <div style="text-align: center">
                       <el-radio v-model="dataForm.templateNum"  label="2">2</el-radio>
                </div>
              </div>
            </div>
          </el-form-item>
<!--          <el-col>-->
<!--            <el-form-item  label="模板编号" prop="templateNum">-->


<!--                <el-radio :label="2">2</el-radio>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogFormAddVisible = false">取消</el-button>
          <el-button  type="primary" @click="add_edit">确定</el-button>
        </span>
      </div>
    </el-dialog>
    <el-dialog
      title="确认删除分类？"
      :visible.sync="dialogFormRemoveVisible"
      :close-on-click-modal="false"
      width="25%"
      :show-close="false"
      :close-on-press-escape="false"
      append-to-body
      center
    >
      <div class="remove-papercate">
        <p>
          当前分类下有数据，
          <br />确认删除该分类及里面包括的所有数据？
        </p>
        <el-form :model="dataForm" @keyup.enter.native="_remove()">
          <el-form-item>
            <el-input v-model="dataForm.confirm" placeholder="请输入DEL已确认" clearable />
          </el-form-item>
          <el-form-item>
            <div class="remove-papercate-buttons">
              <el-button @click="dialogFormRemoveVisible = false">取消</el-button>
              <el-button type="danger" @click="_remove()">确认</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
  <!--<div class="mod-config">
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>-->
</template>

<script>
// import AddOrUpdate from './papercate-add-or-update'

export default {
  data() {
    return {
      arr: [],
      that_data: {},
      that_node: '',
      that_ti: '',
      paperList: {
        display: 'none',
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0
      },
      bool: true,
      dialogcate: 0,
      dialogFormAddVisible: false,
      dialogFormRemoveVisible: false,
      parentName: '',
      dataForm: {
        sort: '',
        name: '',
        confirm: '',
        templateNum: '0'
      },
      dataList: [
        {
          id: 0,
          name: '分类管理目录',
          disabled: true,
          children: []
        }
      ],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  props: {
    rootName: {
      type: String,
      default: '分类管理目录'
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    setCurrent: {
      type: Function,
      default: _ => _ => ({})
    },
    url: {
      type: Object,
      default: _ => ({
        type: 1,
        cateType: 1,
        update: '',
        save: '',
        delete: '',
        tree: ''
      })
    }
  },
  mounted() {
    this.$refs.paper.oncontextmenu = function() {
      return false
    }
    window.addEventListener('click', this.handleClick)
  },
  methods: {
    allowDrop(draggingNode, dropNode, type) {
      if (parseInt(dropNode.data.id)) {
        return type === 'prev'
      } else {
        return true
      }
    },
    handleClick() {
      if (this.paperList.display === 'block') {
        this.paperList.display = 'none'
      }
    },
    mouseup(e, node, data) {
      this.that_data = data
      this.that_node = node
      if (e.button === 2) {
        if (e.y > document.body.clientHeight / 2) {
          this.paperList = {
            display: 'block',
            bottom: `${document.body.clientHeight - e.clientY}px`,
            left: `${e.clientX}px`
          }
        } else {
          this.paperList = {
            display: 'block',
            top: `${e.clientY}px`,
            left: `${e.clientX}px`
          }
        }
      } else {
        this.paperList.display = 'none'
      }
    },
    init(val, bool = true, arr = []) {
      this.that_ti = val
      this.bool = bool
      this.arr = arr
      this.getDataList()
    },
    // modify (e, data) {
    //   this.dataListLoading = true
    //   data.name = e.target.value
    //   this.$http({
    //     url: this.$http.adornUrl(this.url.update),
    //     method: 'post',
    //     data: {
    //       'id': data.id,
    //       'name': e.target.value,
    //       'parentId': data.parentId
    //     }
    //   }).then(res => {
    //     if (res && res.code === 200) {
    //       this.$message({
    //         message: '操作成功',
    //         type: 'success',
    //         duration: 1500
    //       })
    //     } else {
    //       this.$message.warning(res.msg)
    //     }
    //     this.dataListLoading = false
    //   }).catch(_ => {
    //     this.dataListLoading = false
    //   })
    // },
    add_edit_dialog(type) {
      this.paperList.display = 'none'
      this.dataForm.name = ''
      this.dialogcate = type
      this.dialogFormAddVisible = true
      this.that_data.sort = null
      if (parseInt(this.dialogcate) === 1) {
        this.dataForm.name = ''
        this.dataForm.sort = ''
      } else {
        this.dataForm.name = this.that_data.name
        this.dataForm.sort = this.that_data.sort
      }
    },
    handleDrop(draggingNode, dropNode, dropType) {
      this.dialogcate = 0
      this.dataForm.name = draggingNode.data.name
      switch (dropType) {
        case 'before':
          this.that_data.parentId = dropNode.data.parentId
          this.that_data.sort = (dropNode.data.sort - 0.5) * 100
          break
        case 'after':
          this.that_data.parentId = dropNode.data.parentId
          this.that_data.sort = (dropNode.data.sort + 0.5) * 100
          break
        default:
          this.that_data.parentId = dropNode.data.id
          this.that_data.sort = null
          break
      }
      this.that_data.id = draggingNode.data.id
      this.add_edit()
    },
    add_edit() {
      // return false
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl(
          parseInt(this.dialogcate) === 1
            ? this.url.save
            : this.url.update
        ),
        method: 'post',
        data: {
          id: this.that_data.id,
          name: this.dataForm.name,
          sort: this.dataForm.sort ? this.dataForm.sort : this.that_data.sort,
          templateNum: this.dataForm.templateNum,
          parentId:
            parseInt(this.dialogcate) === 1
              ? this.that_data.id || 0
              : this.that_data.parentId
        }
      })
        .then(res => {
          if (res && res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.dialogFormAddVisible = false
            this.getDataList()
            this.dialogcate = 0
          } else {
            this.$message.warning(res.msg)
          }
          this.dataListLoading = false
        })
        .catch(_ => {
          this.dataListLoading = false
        })
    },

    /* remove (node) {
        this.paperList.display = 'none'
        this.that_node = node
        this.dialogFormRemoveVisible = true
        this.$confirm(`确定要进行删除操作吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (data.id) {
            this.$http({
              // url: this.$http.adornUrl(`/exam/${this.type === '试卷分类'?'admin':'ques'}/paper/cate/checkcateisdata`),
              url: this.$http.adornUrl(this.url.delete),
              method: 'post',
              data: {id: data.id}
            }).then(res => {
              if (res && res.code === 200) {
                if (res.data) {
                  this.dialogFormRemoveVisible = true
                } else {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500
                  })
                  this.getDataList()
                }
              } else {
                this.$message.warning(data.msg)
              }
            })
          } else {
            const parent = node.parent
            const children = parent.data.children || parent.data
            const index = children.findIndex(d => d.id === data.id)
            children.splice(index, 1)
          }
        }).catch(_ => ({}))
      }, */
    _remove(node) {
      this.paperList.display = 'none'
      this.that_node = node

      if (this.that_data.id) {
        this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl(this.url.delete),
              method: 'post',
              data: { id: this.that_data.id }
              /* , confirm: this.dataForm.confirm */
            })
              .then(res => {
                if (res && res.code === 200) {
                  // if (res.data) {
                  //   // this.dialogFormRemoveVisible = true
                  // } else {
                  //   // this.dialogFormRemoveVisible = false
                  //   this.$notify.success('操作成功')
                  //   this.getDataList()
                  // }
                  this.$notify.success('操作成功')
                  this.getDataList()
                  this.dataForm.confirm = ''
                } else {
                  this.$message.warning(res.data.msg)
                }
              })
              .catch(_ => this.init())
          })
          .catch(() => {
            this.$notify.info('已取消删除')
          })
      } else {
        const parent = this.that_node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === this.that_data.id)
        children.splice(index, 1)
      }
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl(this.url.tree),
        method: 'post',
        data: {
          page: this.dataForm.key ? '' : this.pageIndex,
          limit: this.pageSize,
          keyword: this.dataForm.key
        }
      }).then(res => {
        if (res && res.code === 200) {
          this.dataList[0].children = res.data
          if (this.arr.length) {
            this.$nextTick(_ => this.$refs.tree.setCheckedKeys(this.arr))
          }
        } else {
          this.dataList = []
        }
        this.dataListLoading = false
      })
    }
  },
  destroyed() {
    window.removeEventListener('click', this.handleClick)
  },
  created() {
    this.dataList[0].name = this.rootName
  }
}
</script>
<style lang="scss">
.kxy-paper {
  position: relative;
  min-width: 270px;
  width: 100%;
  height: 100%;
  overflow: auto;
  border: 1px solid #ebeef5;

  .el-tree-node__content {
    height: 32px;
  }

  .custom-tree-node {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    /*input {*/
    /*    border: 0;*/
    /*    padding: 2px 5px;*/
    /*    font-size: 14px;*/
    /*    width: 85px;*/
    /*    height: 20px;*/
    /*    line-height: 16px;*/
    /*}*/

    .custom-tree-node-box {
      display: flex;
      flex: 1;
      align-items: center;

      .label {
        margin-left: 12px;
        line-height: 20px;
        width: 250px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .actions {
        display: flex;
        flex: 1;
        margin-left: 10px;
        justify-content: flex-end;

        .action-item {
          height: 20px;
          width: 20px;
          margin-right: 6px;
        }

        .el-button--text {
          font-size: 13px;
          color: #606266;
        }
      }
    }
  }
}

.paperList {
  position: fixed;
  z-index: 999999;
  background: #f4f4f4;
  list-style-type: none;
  padding: 5px 0;
  border: 1px solid #d1d1d1;
  border-radius: 5px;
  box-shadow: 1px 5px 10px #d9d9d9;
  overflow: hidden;

  li {
    padding: 0 10px;
    color: #333;

    .el-button--mini {
      padding: 5px 2px;
      font-size: 13px;
    }

    .el-button--text {
      color: #333;
    }

    &:hover {
      background: #409eff;

      .el-button--text {
        color: #fff;
      }
    }
  }
}

.remove-papercate {
  padding: 10px;

  p {
    text-align: center;
  }

  .remove-papercate-buttons {
    display: flex;
    justify-content: space-around;

    button {
      width: 100px;
    }
  }
}
</style>
